﻿using System;
using KuiHuaBaoDian.Services.Battle.Entity;
using KuiHuaBaoDian.Services.Lockstep;

namespace KuiHuaBaoDian.Services.Battle.Behaviour {

    /// <summary>
    /// 攻击命中行为
    /// </summary>
    public interface IBattleBehaviour_Hit : IBattleBehaviour {

        /// <summary>
        /// 实体
        /// </summary>
        new public interface IEntity : IBattleBehaviour.IEntity {

            /// <summary>
            /// 攻击时的快照
            /// </summary>
            IDFR_BattleAttackSnapshot AttackSnapshot { get; }

            /// <summary>
            /// 目标实体ID
            /// </summary>
            BattleEntityInstanceID TargetEntityInstanceID { get; }

            /// <summary>
            /// 目标地图位置提供者
            /// </summary>
            IBattleMapPositionProvider TargetMapPositionProvider { get; }
        }
    }

    [Implement(typeof(IBattleBehaviour_Hit))]
    internal sealed class KHBD_BattleBehaviour_Hit : KHBD_BattleBehaviour, IBattleBehaviour_Hit {

        new private IBattleBehaviour_Hit.IEntity Entity => (IBattleBehaviour_Hit.IEntity)base.Entity;

        private LockstepTimerCancellationToken m_DelayTimerCancellationToken;

        protected override void Initialize() {
        }

        protected override void Dispose() {
            if (m_DelayTimerCancellationToken != null) {
                m_DelayTimerCancellationToken.Cancel();
                m_DelayTimerCancellationToken = null;
            }
            base.Dispose();
        }

        protected override IBattleBehaviourInfo LogicFrame() {
            m_DelayTimerCancellationToken = new LockstepTimerCancellationToken();
            LockstepTimerService.Instance.Start((F64)BattleServiceBase.BATTLE_BULLET_HIT_TIME, 1, onComplete: data => {
                BattleAttackService.Instance.Hit(Entity.AttackSnapshot, Entity.TargetEntityInstanceID, Entity.TargetMapPositionProvider,
                    sourceModelDictionary: DFR_BattleBase.DataCenter.Models.AttackSourceDictionary,
                    targetModelDictionary: DFR_BattleBase.DataCenter.Models.AttackTargetDictionary);
            }, cancellationToken: m_DelayTimerCancellationToken);

            return new KHBD_BattleBehaviourInfo {
                Type = BattleBehaviourType.Hit,
            };
        }

        protected override void Execute(IBattleBehaviourInfo info) {
        }

        protected override void Update(IBattleBehaviourInfo info, float interpolation) {
            StateMachine.State = BattleEntityState.Attack;
        }
    }
}
